function h = scaleimage(cdata, varargin)
% scaleimage  - automatically scale image data for image
%
% FORMAT:       [h = ] scaleimage(C, ...)
%
% Input fields:
%
%       C           MxN image data that is shown with a 256 grayscale
%       ...         additional arguments passed to image
%
% Output fields:
%
%       h           image handle

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% persistent last handle
persistent i_scilasth;
if isempty(i_scilasth)
    i_scilasth = -1;
end

% argument check
if ~isnumeric(cdata) || ...
    ndims(cdata) > 2
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid color data given.' ...
    );
end
mmm = minmaxmean(cdata, 4);
cds = floor(1 + (255.99 / (eps + mmm(2) - mmm(1))) .* (double(cdata) - mmm(1)));
if nargin < 3 || ...
   ~ischar(varargin{end-1}) || ...
   ~any(strcmpi(varargin{end-1}(:)', {'image', 'parent'})) || ...
   ~isa(varargin{end}, 'double') || ...
    numel(varargin{end}) ~= 1 || ...
   ~ishandle(varargin{end}) || ...
   ~any(strcmpi(get(varargin{end}, 'Type'), {'axes', 'image'}))
    if ishandle(i_scilasth)
        h = i_scilasth;
        set(h, 'CData', cds);
    else
        h = image(cds, varargin{:});
        i_scilasth = h;
        colormap((0:1/255:1)' * ones(1,3));
    end
else
    if strcmpi(get(varargin{end}, 'Type'), 'image')
        h = varargin{end};
        set(h, 'CData', cds);
    else
        h = image(cds, varargin{:});
        i_scilasth = h;
    end
end
drawnow;
